/*
 * Kaleidoscope application
 * Describes a triangle
 *
 * Luke Mitchell 05-04-12
 */

import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.lang.Boolean;
import java.util.ArrayList;

public class Triangle
{
    private Point x, y, z;
    private Polygon poly;

    // public get functions
    public Point getX () { return x; }
    public Point getY () { return y; }
    public Point getZ () { return z; }

    // returns true if the point is contained within
    // the triangles confines
    public Boolean contains (Point p)
    {
        // TODO - return true if most of the pixel is contained
        return poly.contains (p);
    }

    // returns an array of points contained within the triangle
    public Point[] contained ()
    {
        Point[] contained;
        ArrayList<Point> points = new ArrayList<Point> ();
        
        // get bounding box
        Rectangle rect = poly.getBounds ();
        
        // check each point within the bounding box (ignoring partial numbers)
        for (int y = Common.dtoi (rect.getY ()); y <= Common.dtoi (rect.getY () + rect.getHeight ()); y++)
            for (int x = Common.dtoi (rect.getX ()); x <= Common.dtoi (rect.getX () + rect.getWidth ()); x++)
                if (this.contains (new Point (x, y)))
                    points.add (new Point (x, y));

        contained = new Point[points.size ()];

        return points.toArray (contained);
    }

    // ctors
    private void construct (Point x, Point y, Point z)
    {
        this.x = x;
        this.y = y;
        this.z = z;

        poly = new Polygon ();
        poly.addPoint (Common.dtoi (x.getX ()), Common.dtoi(x.getY ()));
        poly.addPoint (Common.dtoi (y.getX ()), Common.dtoi (y.getY ()));
        poly.addPoint (Common.dtoi (z.getX ()), Common.dtoi (z.getY ()));
    }

    public Triangle (Point x, Point y, Point z)
    {
        construct (x, y, z);
    }

    public Triangle (int xx, int xy, int yx, int yy, int zx, int zy)
    {
        construct (new Point (xx, xy), new Point (yx, yy), new Point (zx, zy));
    }

    // main method
    public static void main (String[] args)
    {
        Triangle t = new Triangle (0, 0, 5, 0, 5, 6);
        System.out.println ("Creating triangle (0,0) (5,0) (5,6)");

        Boolean result = t.contains (new Point (4, 4));
        System.out.println ("\tTriangle contains (4,4) came back as " + result + " (should be true)");

        Point[] p = t.contained ();
        System.out.println ("\tTriangle contains the following coordinates:");
        for (int i = 0; i < p.length; i++)
            System.out.println ("\t\t" + p[i]);
    }
}
